<template>
    <div class="main">
        <div class="main-div">
            <!-- 作业标题 -->
            <h2 class="homework-title">{{ homeworkTitle }}</h2>
            <!-- 文件 -->
            <div class="file">
                <div style="margin-bottom: 1rem">
                    <el-upload class="file-upload" action="#" :auto-upload="false" :show-file-list="true"
                        :multiple="true" accept="image/*" drag @change="handleImageUpload">
                        <div class="file-upload-div">
                            <el-icon class="file-upload-div-icon">
                                <Upload />
                            </el-icon>
                            <div class="click">点击或将文件拖拽到此区域上传</div>
                            <div class="clicks">支持批量上传图片文件</div>
                        </div>
                    </el-upload>
                </div>
                <el-input v-model="searchQuery" placeholder="搜索学生姓名或学号..." style="width: 100%;">
                    <template #prefix>
                        <el-icon>
                            <Search />
                        </el-icon>
                    </template>
                </el-input>
            </div>
            <!-- 进度条 -->
            <div v-if="importing" style="margin-bottom: 2rem;">
                <el-progress :percentage="importProgress" :format="format" style="margin-bottom: 0.5rem;" />
                <p class="click">正在导入数据... {{ importProgress }}%</p>
            </div>
            <!-- 筛选区域 -->
            <div class="sift">
                <div class="sift-div">
                    <span class="click">分数区间：</span>
                    <el-input-number v-model="scoreRange.min" :min="0" :max="100" placeholder="最低" style="width: 5rem;"
                        controls-position="right" />
                    <span>-</span>
                    <el-input-number v-model="scoreRange.max" :min="0" :max="100" placeholder="最高" style="width: 5rem;"
                        controls-position="right" />
                </div>
                <el-button :type="filterStatus === 'completed' ? 'primary' : 'default'"
                    @click="filterStatus = filterStatus === 'completed' ? '' : 'completed'"
                    style="white-space: nowrap;">
                    已完成
                </el-button>
                <el-button :type="filterStatus === 'incomplete' ? 'primary' : 'default'"
                    @click="filterStatus = filterStatus === 'incomplete' ? '' : 'incomplete'"
                    style="white-space: nowrap;">
                    未完成
                </el-button>
                <el-button v-if="hasFilters" text @click="clearFilters" style="white-space: nowrap;">
                    <el-icon style="margin-right: 0.25rem;">
                        <Close />
                    </el-icon>清除筛选
                </el-button>
            </div>
            <!-- 学生列表 -->
            <div class="el-table-container">
                <el-table :data="filteredStudents" style="width: 100%;" @sort-change="handleSortChange" height="500">
                    <el-table-column prop="id" label="学号" sortable="custom" />
                    <el-table-column prop="name" label="姓名" />
                    <el-table-column prop="score" label="得分" sortable="custom" />
                    <el-table-column prop="status" label="状态">
                        <template #default="scope">
                            <el-tag :type="scope.row.status === 'completed' ? 'success' : 'warning'" effect="light">
                                {{ scope.row.status === 'completed' ? '已完成' : '未完成' }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="120">
                        <template #default="scope">
                            <el-button link type="primary" @click="showStudentDetail(scope.row)"
                                style="white-space: nowrap;">
                                <el-icon style="margin-right: 0.25rem;">
                                    <View />
                                </el-icon>查看详情
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <!-- 底部功能区 -->
            <div class="function">
                <p class="function-text">
                    共 {{ filteredStudents.length }} 名学生
                </p>
                <el-button type="primary" @click="exportData" style="white-space: nowrap;">
                    <el-icon style="margin-right: 0.5rem;">
                        <Download />
                    </el-icon>导出数据
                </el-button>
            </div>
        </div>
        <!-- 学生详情弹窗 -->
        <el-dialog v-model="dialogVisible" title="学生详情" width="50%">
            <div class="space-y-4">
                <el-descriptions :column="2" border>
                    <el-descriptions-item label="学号">{{ selectedStudent?.id }}</el-descriptions-item>
                    <el-descriptions-item label="姓名">{{ selectedStudent?.name }}</el-descriptions-item>
                    <el-descriptions-item label="得分">{{ selectedStudent?.score }}</el-descriptions-item>
                    <el-descriptions-item label="提交时间">{{ selectedStudent?.submitTime }}</el-descriptions-item>
                    <el-descriptions-item label="教师评语" :span="2">
                        {{ selectedStudent?.feedback }}
                    </el-descriptions-item>
                </el-descriptions>
            </div>
        </el-dialog>

        <!-- Student组件弹窗 -->
        <el-dialog v-model="showStudent">
            <component :is="StudentComponent" />
            <template #footer>
                <span class="dialog-footer">
                    <el-button type="primary" @click="showStudent = false">关闭</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>
<script lang="ts" setup>
import { ref, computed, defineAsyncComponent } from 'vue';
import { Search, Upload, Close, View, Download } from '@element-plus/icons-vue';
import type { TableColumnCtx } from 'element-plus';

// 使用异步组件导入Student
const StudentComponent = defineAsyncComponent(() => import('./Student.vue'));

defineProps<{
    homeworkTitle: string
}>();

interface Student {
    id: string;
    name: string;
    score: number;
    status: string;
    submitTime: string;
    feedback: string;
}
const importing = ref(false);
const importProgress = ref(0);
const searchQuery = ref('');
const scoreRange = ref({ min: '', max: '' });
const filterStatus = ref('');
const selectedStudent = ref<Student | null>(null);
const dialogVisible = ref(false);
const showStudent = ref(false);
const displayedStudents = ref<Student[]>([]);
const allStudents = ref<Student[]>([]);
const currentBatch = ref(0);
const batchSize = 2;
// 模拟学生数据
const students = ref<Student[]>([
    { id: '2021001', name: '张雨晨', score: 95, status: 'completed', submitTime: '2023-12-01 14:30', feedback: '作业完成度高，思路清晰，有独到见解。建议在细节处理上可以更加严谨。' },
    { id: '2021002', name: '李明阳', score: 88, status: 'completed', submitTime: '2023-12-01 15:20', feedback: '整体表现良好，概念掌握准确，部分习题需要加强练习。' },
    { id: '2021003', name: '王子涵', score: 76, status: 'completed', submitTime: '2023-12-01 16:45', feedback: '基础知识掌握尚可，需要加强解题技巧的训练。' },
    { id: '2021004', name: '赵梦琪', score: 92, status: 'completed', submitTime: '2023-12-01 13:15', feedback: '逻辑思维能力强，解题方法灵活，继续保持。' },
    { id: '2021005', name: '刘浩然', score: 0, status: 'incomplete', submitTime: '-', feedback: '未提交作业，请及时补交。' },
    { id: '2021006', name: '陈思远', score: 85, status: 'completed', submitTime: '2023-12-01 17:00', feedback: '作业认真完成，部分难点题目需要加强理解。' },
    { id: '2021007', name: '周雪婷', score: 90, status: 'completed', submitTime: '2023-12-01 14:50', feedback: '理解深入，表达准确，建议多尝试不同解法。' },
    { id: '2021008', name: '杨云帆', score: 0, status: 'incomplete', submitTime: '-', feedback: '未提交作业，请尽快完成。' },

]);
const hasFilters = computed(() => {
    return searchQuery.value || scoreRange.value.min || scoreRange.value.max || filterStatus.value;
});
const filteredStudents = computed(() => {
    let result = [...displayedStudents.value];
    // 搜索过滤
    if (searchQuery.value) {
        const query = searchQuery.value.toLowerCase();
        result = result.filter(student =>
            student.name.toLowerCase().includes(query) ||
            student.id.toLowerCase().includes(query)
        );
    }
    // 分数区间过滤
    if (scoreRange.value.min) {
        result = result.filter(student => student.score >= Number(scoreRange.value.min));
    }
    if (scoreRange.value.max) {
        result = result.filter(student => student.score <= Number(scoreRange.value.max));
    }
    // 状态过滤
    if (filterStatus.value) {
        result = result.filter(student => student.status === filterStatus.value);
    }
    return result;
});
const handleSortChange = (column: TableColumnCtx<Student>) => {
    if (!column.prop || !column.order) return;
    students.value.sort((a, b) => {
        const prop = column.prop as keyof Student;
        if (column.order === 'ascending') {
            return a[prop] > b[prop] ? 1 : -1;
        } else {
            return a[prop] < b[prop] ? 1 : -1;
        }
    });
};
const format = (percentage: number) => percentage + '%';
const handleImageUpload = async (file: any) => {
    if (!file.raw) return;
    importing.value = true;
    importProgress.value = 0;
    displayedStudents.value = [];
    currentBatch.value = 0;
    // 重置并准备新的学生数据
    allStudents.value = [...students.value];
    displayedStudents.value = [];
    // 模拟图片处理和数据加载进度
    const totalSteps = 20;
    for (let i = 0; i <= totalSteps; i++) {
        await new Promise(resolve => setTimeout(resolve, 100));
        importProgress.value = Math.floor((i / totalSteps) * 100);
    }
    // 完成导入后开始逐步显示学生数据
    const showNextBatch = () => {
        if (currentBatch.value * batchSize >= allStudents.value.length) {
            importing.value = false;
            return;
        }
        const start = currentBatch.value * batchSize;
        const end = Math.min((currentBatch.value + 1) * batchSize, allStudents.value.length);
        const newStudents = allStudents.value.slice(start, end);
        displayedStudents.value = [...displayedStudents.value, ...newStudents];
        currentBatch.value++;
        if (currentBatch.value * batchSize < allStudents.value.length) {
            setTimeout(showNextBatch, 500);
        } else {
            importing.value = false;
        }
    };
    setTimeout(showNextBatch, 500);
};
const showStudentDetail = (student: Student) => {
    selectedStudent.value = student;
    showStudent.value = true; // 显示Student组件
};
const clearFilters = () => {
    searchQuery.value = '';
    scoreRange.value = { min: '', max: '' };
    filterStatus.value = '';
};
const exportData = () => {
    // 模拟导出功能
    console.log('Exporting data...');
};
</script>
<style scoped>
:deep(.el-input-number .el-input__wrapper) {
    padding-left: 8px;
    padding-right: 8px;
}

:deep(.el-input-number.is-controls-right .el-input__wrapper) {
    padding-left: 8px;
    padding-right: 25px;
}

:deep(.el-upload-dragger) {
    width: 100%;
    height: auto;
    background: none;
    border: none;
}

:deep(.el-upload) {
    width: 100%;
}

.main {
    /* padding-top: 2rem;
    padding-bottom: 2rem; */
    background-color: #F9FAFB;
    overflow-y: auto;
    max-height: calc(100vh - 120px);
    height: calc(100vh - 120px);
}

.main-div {
    padding-left: 1rem;
    padding-right: 1rem;
    max-width: 80rem;
    margin: 0 auto;
    width: 100%;
}

.file {
    margin-bottom: 2rem;
}

.file-upload {
    display: flex;
    flex-direction: column;
    align-items: center;
}

.file-upload-div {
    padding: 2rem;
    border-radius: 0.5rem;
    border-width: 2px;
    border-color: #D1D5DB;
    border-style: dashed;
    width: 100%;
    cursor: pointer;
}

.file-upload-div:hover {
    border-color: #6B7280;
}

.file-upload-div-icon {
    margin-bottom: 1rem;
    font-size: 2.25rem;
    line-height: 2.5rem;
    color: #9CA3AF;
}

.click {
    font-size: 0.875rem;
    line-height: 1.25rem;
    color: #4B5563;
}

.clicks {
    margin-top: 0.25rem;
    font-size: 0.75rem;
    line-height: 1rem;
    color: #6B7280;
}

.sift {
    display: flex;
    margin-bottom: 1.5rem;
    gap: 1rem;
    align-items: center;
}
.sift-div{
    display: flex; 
gap: 0.5rem; 
align-items: center; 
}
.function{
    display: flex; 
padding-top: 1rem;
padding-bottom: 1rem; 
justify-content: space-between; 
align-items: center; 
}
.function-text{
    font-size: 0.875rem;
line-height: 1.25rem; 
color: #4B5563;
}
.homework-title {
    font-size: 1.5rem;
    font-weight: 600;
    color: #111827;
    /* margin-bottom: 1.5rem; */
    padding-bottom: 0.75rem;
    border-bottom: 1px solid #E5E7EB;
}

:deep(.el-table) {
    max-height: none !important;
}

:deep(.el-table__body-wrapper) {
    overflow-y: auto !important;
}

.el-table-container {
    margin-bottom: 2rem;
}
</style>